package com.hz.zbl.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hz.zbl.helper.UserHelper;
import com.hz.zbl.mapper.ClassMapper;
import com.hz.zbl.mapper.GradeMapper;
import com.hz.zbl.mapper.UserMapper;
import com.hz.zbl.model.entity.ClassEntity;
import com.hz.zbl.model.entity.GradeEntity;
import com.hz.zbl.model.entity.UserEntity;
import com.hz.zbl.model.enums.ApiResponseCodeEnum;
import com.hz.zbl.model.enums.UserTypeEnum;
import com.hz.zbl.model.request.ApiResponse;
import com.hz.zbl.service.UserManagerService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserManagerServiceImpl implements UserManagerService {

    @Resource
    GradeMapper gradeMapper;

    @Resource
    ClassMapper classMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    RedisTemplate redisTemplate;


    //添加年级
    @Override
    public int addGrade(String grade_name, String grade_year) {

        if (gradeMapper.selectGradeByName(grade_name) != null){
            return 0;
        }else {
            GradeEntity gradeEntity = new GradeEntity();

            gradeEntity.setGrade_name(grade_name);
            gradeEntity.setGrade_year(grade_year);

            return gradeMapper.addGrade(gradeEntity);
        }
    }


    //添加班级
    @Override
    public int addClass(String class_name, Integer grade_id) {
        //班级名是否重复或者年级是否存在
        if(classMapper.selectClassByName(class_name) != null
            || gradeMapper.selectGradeById(grade_id) == null){

            return 0;
        }else {
            ClassEntity classEntity = new ClassEntity();
            GradeEntity gradeEntity = gradeMapper.selectGradeById(grade_id);

            classEntity.setGrade_id(grade_id);
            classEntity.setClass_name(class_name);
            classEntity.setGrade_name(gradeEntity.getGrade_name());
            classEntity.setGrade_year(gradeEntity.getGrade_year());

            return classMapper.addClass(classEntity);
        }

    }


    //添加管理员
    @Override
    public int addManager(String username, String realname, String password) {
        UserEntity userEntity = userMapper.selectByUnameAndUtype(username, UserTypeEnum.MANAGER.getUser_type());
        if (userEntity != null){
            return 0;
        }else {
            UserEntity manager = new UserEntity();
            manager.setUsername(username);
            manager.setRealname(realname);
            manager.setUser_type(UserTypeEnum.MANAGER.getUser_type());


            String salt = UUID.randomUUID().toString();
            String pwd = UserHelper.createNewPwd(password, salt, username);

            manager.setPwd_salt(salt);
            manager.setPwd(pwd);


            manager.setPwd_valid_date(System.currentTimeMillis() + 7 * 23 * 3600 * 1000);

            manager.setPwd_error_count(0);

            System.out.println(manager);
            return userMapper.addManager(manager);

        }
    }

    //添加老师
    @Override
    public int addTeacher(String username, String realname, String password, Integer teacher_id) {
        UserEntity ifExist = userMapper.selectByUnameAndUtype(username,UserTypeEnum.TEACHER.getUser_type());
        if (ifExist != null){
            return 0;
        }else {
            UserEntity teacher = new UserEntity();

            teacher.setUsername(username);
            teacher.setRealname(realname);
            teacher.setTeacher_id(teacher_id);
            teacher.setUser_type(UserTypeEnum.TEACHER.getUser_type());

            String salt = UUID.randomUUID().toString();
            String pwd = UserHelper.createNewPwd(password,salt,username);

            teacher.setPwd_salt(salt);
            teacher.setPwd(pwd);

            teacher.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
            teacher.setPwd_error_count(0);

            return userMapper.addTeacher(teacher);
        }

    }

    //添加学生
    @Override
    public int addStudent(String username, String realname, String password, int student_id, Integer class_id, Integer grade_id) {
        UserEntity ifExist = userMapper.selectByUnameAndUtype(username,UserTypeEnum.STUDENT.getUser_type());
        if (ifExist != null){
            return 0;
        }else {
            UserEntity student = new UserEntity();

            student.setUsername(username);
            student.setRealname(realname);
            student.setStudent_id(student_id);
            student.setUser_type(UserTypeEnum.STUDENT.getUser_type());

            String salt = UUID.randomUUID().toString();
            String pwd = UserHelper.createNewPwd(password,salt,username);

            student.setPwd_salt(salt);
            student.setPwd(pwd);

            student.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
            student.setClass_id(class_id);
            student.setGrade_id(grade_id);

            student.setPwd_error_count(0);

            return userMapper.addStudent(student);

        }
    }

//    @Override
//    public String login(String username, String password, Integer user_type) {
//        UserEntity userEntity = userMapper.selectByUnameAndUtype(username, user_type);
//        if (userEntity == null){
//            return null;
//        }
//        String PWD = UserHelper.createNewPwd(password, userEntity.getPwd_salt(), username);
//        if (!PWD.equals(userEntity.getPwd())){
//            return null;
//        }
//
//        redisTemplate.opsForValue().set(username, JSON.toJSONString(userEntity),30, TimeUnit.MINUTES);
//        return JSON.toJSONString(userEntity);
//    }

//

    @Override
    public String login(String username, String password, Integer user_type) {
        UserEntity loginUser = userMapper.selectByUnameAndUtype(username,user_type);
        if (loginUser == null){
            System.out.println(1);
//            return JSON.toJSONString("此账户不存在");
            return null;
        }
        //判断账号登录错误次数是否超过3次，超过则登陆失败，在前段返回提示，账号登录错误次数过多，已锁定
        else if (loginUser.getPwd_error_count() > 3) {
            System.out.println(2);
//            return JSON.toJSONString("此账户已被锁定，请联系管理员认证身份解除锁定");
            return null;
        }

        //判断密码有效期是否过期，过期则登录失败，前段返回提示，密码修改
        else if (loginUser.getPwd_valid_date() < System.currentTimeMillis() +  24 * 3600 * 1000) {
            System.out.println(3);
//            return JSON.toJSONString("此账户密码有效期已过，请联系管理员修改密码");
            return null;
        } else if (!loginUser.getPwd().equals(UserHelper.createNewPwd(password,loginUser.getPwd_salt(),username))){
            System.out.println(4);
            userMapper.updatePwdErrorCount(loginUser.getId(), loginUser.getPwd_error_count() + 1);
//            return JSON.toJSONString("密码错误");
            return null;
        }

        //登陆成功，重置所有登录错误次数
        else {

            userMapper.updatePwdErrorCount(loginUser.getId(), 0);
            redisTemplate.opsForValue().set(username, JSON.toJSONString(loginUser), 30, TimeUnit.MINUTES);
            return JSON.toJSONString(loginUser);
        }
    }


    @Override
    public int logout(String username) {
        redisTemplate.delete(username);
        return 1;
    }

    @Override
    public int changePwd(int id, String orignPwd, String newPwd, String newPwdConfirm) {
        UserEntity user = userMapper.selectByUid(id);
        String inputPwd = UserHelper.createNewPwd(orignPwd, user.getPwd_salt(), user.getUsername());


        //用户是否存在
        if (user == null){
            return 0;
        }
        //输入原密码是否与数据库原密码相同
        else if (!inputPwd.equals(user.getPwd())) {
            return 1;
        }
        //新密码是否与旧密码相同
        else if (newPwd.equals(orignPwd)){
            return 2;
        }
        //两次新密码是否相同
        else if (!newPwd.equals(newPwdConfirm)) {
            return 3;
        }else {
            String newSqlPwd = UserHelper.createNewPwd(newPwd, user.getPwd_salt(), user.getUsername());
            userMapper.updatePwd(id, newSqlPwd, System.currentTimeMillis() + 7 *24 * 3600 * 1000);
            return 4;
        }

    }


}
